package com.NetWork.lesson3;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

public class TalkReceive implements Runnable {
    DatagramSocket socket = null;
    private int port;
    private String msfFrom;

    public TalkReceive(int port, String msfFrom) {
        this.port = port;
        this.msfFrom = msfFrom;
        try {
            socket = new DatagramSocket(this.port);
        } catch (SocketException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void run() {

        while (true){
            try {
                //准备接受packet
                byte[] contianer = new byte[1024];
                DatagramPacket packet = new DatagramPacket(contianer,0,contianer.length);
                socket.receive(packet);//阻塞式接受包裹
                //断开连接
                byte[] data = packet.getData();
                String receivedata = new String(data, 0, data.length);
                System.out.println(msfFrom+":"+receivedata);
                if (receivedata.equals("q")){
                    break;
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        socket.close();
    }
}

    